<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\model\Config;
use fast\Http;
use app\api\model\Deal;
use app\api\model\User;
use think\Request;

/**
 * 首页接口
 */
class Index extends Api
{

    protected $noNeedLogin = ['getToken','userid','test'];
    protected $noNeedRight = ['*'];
    protected $failException = true;



    /**
     * 首页
     *
     */
    public function index()
    {
        $user = $this->auth->getUser();
        $data = Http::get(config('sac_url'));
        $data = json_decode($data, true);
        $price = end($data['price_usd'])[1];        //比特币
        $volume = end($data['volume_usd'])[1];
        $market = end($data['market_cap_usd'])[1];
        $rate = floatval(config('site.rate'));
        $localprice = config('site.localprice'); //人民币
        //cny 数量
        //$cny = $user->cny+$user->sac*$price*$rate;
        $cny = $user->cny+$user->sac*$localprice;
        // banner图
        $banner = db('Banner')->field('id,image')->order('addtime desc')->select();
        //币种信息
        $coin = db('Coin')->field('id,title,image,status')->select();
        foreach($coin as $k=>$v){
            if($v['status']==2){
                $coin[$k]['num'] = $user->sac;
                $coin[$k]['cny'] = round($user->sac*$localprice,4);
            }else{
                $coin[$k]['num'] = 0;
                $coin[$k]['cny'] = 0;
            }
        }
        $data = [
            'cny' => round($cny,4),
            'banner'=>$banner,
            'coin'=>$coin,
            'sacprice'=>round($localprice,4)
        ];
        $this->success('success', $data);
    }
    /**
     * banner图详情
     */
    public function banner(){
        $id = input('id');
        $data = db('Banner')->where(['id'=>$id])->find();
        $data['content'] = str_replace('<img src="', '<img src="http://cnynew.hg8851.cn', $data['content']);
        $this->success('success', $data);
    }
    /**
     * sac股权
     */
    public function equity(){
        //账户总金额
        $user = $this->auth->getUser();
        //查出股权列表
        $list = db('equity')->select();
        $totalcny = 0;
        foreach($list as $k=>$v){
            //查到该币种所持有的值
            $num = db('user_equity')->where(['user_id'=>$user->id,'status'=>1,'equity_id'=>$v['id']])->find();
            if($num){
                $list[$k]['num'] = ($num['money']-$num['c_money'])/config('stocks');
            }else{
                $list[$k]['num'] = 0;
            }
            $totalcny += $num['money'];
            //查询昨日收益
            $earn = db('equity_cny')->where(['user_id'=>$user->id,'equity_id'=>$v['id']])->whereTime('addtime', 'yesterday')->sum('money');
            $list[$k]['earn'] = $earn;
        }
        $data = ['equity'=>$list,'totalcny'=>$totalcny];
        $this->success('success', $data);

    }
    /**
     * 购买股权页面
     */
    public function buyequity(){
        $user = $this->auth->getUser();
        $id = input('id');
        //查询该股权的信息
        $equity = db('equity')->where(['id'=>$id])->find();
        $this->success('success', $equity);
    }
    /**
     * 购买股权方法
     */
    public function buyfunc(){
        //用户信息
        $user = $this->auth->getUser();
        //购买数量
        $num = input('num');
        if($num<=0){
            $this->error('购买数量不能小于0');
        }
        //购买基金id
        $id = input('id');
        if(!$id){
            $this->error('参数错误');
        }
        //判断基金是否存在
        $equity = db('equity')->where(['id'=>$id])->find();
        if(!$equity){
            $this->error('基金不存在');
        }
        $coin = $num*config('stocks');
        //判断可用币是否满足
        if($user->cny<$coin){
            $this->error('cny数量不足');
        }
        $pay_password = input('pay_password');
        if(!$pay_password){
            $this->error('支付密码不能空');
        }
        //判断密码正确
        $pay_password = $this->auth->getEncryptPassword($pay_password, $user->salt);
        if ($user->pay_password != $pay_password) {
            $this->error('支付密码不正确');
        }
        //判断是否到达购买限制
        $user_equity = db('user_equity')->where(['user_id'=>$user->id,'status'=>1])->find();
        if(($user_equity['money']-$user_equity['c_money'])/config('stocks')+$num>$equity['limit']){
            $this->error('超出限购数量');
        }
        //扣除资金
        $r = db('user')->where(['id'=>$user->id])->setDec('cny',$coin);
        //加入财务日志
        account_log($user->id,$coin*(-1),$user->cny - $coin + $user->freeze_cny,0,$user->sac+$user->freeze_sac,'用户ID:'.$user->id.'购买基金'.$equity['title'].$num.'股,合cny:'.$coin);
        //加入用户购买基金表
        //查看这个用户是否有正在运行的基金
        $res = db('user_equity')->where(['user_id'=>$user->id,'status'=>1])->find();
        if($res){
            //有 修改原来的股权份数  刷新最后一次操作时间
            $up['caotime'] = time();
            $up['money'] = $res['money']+$coin;
            db('user_equity')->where(['id'=>$res['id']])->update($up);
        }else{
            //没有  新增一条记录
            $ins['user_id'] = $user->id;
            $ins['equity_id'] = $id;
            $ins['c_money'] = 0;
            $ins['money'] = $coin;
            $ins['status'] = 1;
            $ins['addtime'] = time();
            $ins['caotime'] = time();
            db('user_equity')->insert($ins);
        }
        
        //完成收工
        $this->success('购买成功');
    }
    /**
     * 证券收益
     */
    public function equityrecord(){
        //用户信息
        $user = $this->auth->getUser();
        //接收购买股权id
        $equity_user_id = input('equity_user_id');
        //查询产币记录
        $list = db('equity_cny')->field('id,equity_id,addtime,money,equity_user_id,num')->where(['equity_user_id'=>$equity_user_id])->order('addtime desc')->select();
        foreach($list as $k=>$v){
            //查询基金信息
            $equity = db('equity')->where(['id'=>$v['equity_id']])->find();
            $list[$k]['title'] = $equity['title'];
            $list[$k]['odds'] = $equity['odds'];
            $list[$k]['addtime'] = date('Y-m-d H:i:s',$v['addtime']);
            $list[$k]['num'] = $v['num'];
        }
        $this->success('查询成功',$list);
    }
    /**
     * 购买记录
     */
    public function buyrecord(){
        //用户信息
        $user = $this->auth->getUser();
        //页数
        $page = input('page')?input('page'):1;
        //条数
        $limit = input('limit')?input('limit'):5;
        //开始时间
        $start = input('start');
        //结束时间
        $end = input('end');
        if($start){
            $start = strtotime($start);
            $where['addtime'] = ['>',$start];
        }
        if($end){
            $end = strtotime($end);
            $where['addtime'] = ['<',$end];
        }
        if($start && $end){
            $where['addtime'] = ['between',[$start,$end]];
        }
        $where['user_id'] = $user->id;
        //查询购买记录
        $list = db('user_equity')->field('id,c_money,money,addtime,status,equity_id')->where($where)->order('addtime desc')->page($page,$limit)->select();
        foreach($list as $k=>$v){
            //查询基金信息
            $equity = db('equity')->where(['id'=>$v['equity_id']])->find();
            $list[$k]['title'] = $equity['title'];
            $list[$k]['money'] = $v['money'];
            $list[$k]['c_money'] = $v['c_money'];
            $list[$k]['addtime'] = date('Y-m-d H:i:s',$v['addtime']);
        }
        $data['list'] = $list;
        $data['count'] = db('user_equity')->field('id,money,addtime,status,equity_id')->where($where)->count();
        $this->success('查询成功',$data);
    }
    /**
     * 转账方法
     */
    public function transfer(){
        $user = $this->auth->getUser();
        //转账地址
        $address = input('address');
        if(empty($address)){
            $this->error('转账地址不能空');
        }
        //查询收账人信息
        $shou = db('user')->where(['cny_address'=>$address])->find();
        if(!$shou){
            $this->error('转账地址不存在');
        }
        $pay_password = input('pay_password');
        if(!$pay_password){
            $this->error('支付密码不能空');
        }
        //判断密码正确
        $pay_password = $this->auth->getEncryptPassword($pay_password, $user->salt);
        if ($user->pay_password != $pay_password) {
            $this->error('支付密码不正确');
        }
        //转账金额
        $num = input('num');
        if($num<=0){
            $this->error('转账数量不能小于0');
        }
        //判断转账人金额是否充足
        if($user->cny<$num){
            $this->error('转账数量不足');
        }
        //开始扣币转账
        //1 扣转账人的币
        $r = db('user')->where(['id'=>$user->id])->setDec('cny',$num);
        //2 增加财务日志
        account_log($user->id,$num*(-1),$user->cny - $num + $user->freeze_cny,0,$user->sac+$user->freeze_sac,'向用户ID:'.$shou['id'].'转账'.$num.'cny');
        //3 增加收账人币
        $res = db('user')->where(['id'=>$shou['id']])->setInc('cny',$num);
        //4 增加收账人财务日志
        account_log($shou['id'],$num,$user->cny + $num + $user->freeze_cny,0,$user->sac+$user->freeze_sac,'从用户ID:'.$user->id.'收账'.$num.'cny');
        //增加转出数据
        $data['suser_id'] = $shou['id'];
        $data['user_id'] = $user->id;
        $data['type'] = 1;
        $data['money'] = $num;
        $data['addtime'] = time();
        db('transfer')->insert($data);
        //增加转入数据
        $data['suser_id'] = $user->id;
        $data['user_id'] = $shou['id'];
        $data['type'] = 2;
        $data['money'] = $num;
        $data['addtime'] = time();
        db('transfer')->insert($data);
        //完事收工
        $this->success('转账完成');
    }
    /**
     * 转账记录
     */
    public function transferlist(){
        $user = $this->auth->getUser();
        $type = input('type');
        if($type){
            $where['type'] = $type;
        }
        //页数
        $page = input('page')?input('page'):1;
        //条数
        $limit = input('limit')?input('limit'):5;
        $where['user_id'] = $user->id;
        $list =  db('transfer')->where($where)->order('addtime desc')->page($page,$limit)->select();
        foreach($list as $k=>$v){
            $list[$k]['suser_info'] = db('user')->where(['id'=>$v['suser_id']])->find();
        }
        $count = db('transfer')->where($where)->order('addtime desc')->count();
        $data['list'] = $list;
        $data['count'] = $count;
        $this->success('查询成功',$data);
    }
    /**
     * 转账页面
     */
    public function transferIndex(){
        $user = $this->auth->getUser();
        $data['cny'] = $user->cny;
        $this->success('加载完成',$data);
    }
    /**
     * 挖宝页面
     */
    public function Indian(){
        $user = $this->auth->getUser();
        //sac 的价格
        $data = Http::get(config('sac_url'));
        $data = json_decode($data, true);
        $localprice = config('site.localprice');
        $price = end($data['price_usd'])[1]; //美元价格
        $rate = floatval(config('site.rate')); // 美元汇率
        $force = 0;
        $sac = 0;
        $star = 0;
        //我的算力 就是我拥有的矿机
        $where['status'] = 1;
        $where['user_id'] = $user->id;
        $mymill = db('user_mill')->where($where)->select();
        if($mymill){
            foreach($mymill as $k=>$v){
                //查矿机信息
                $mill = db('mill')->where(['id'=>$v['mill_id']])->find();
                //算力
                $force+=($mill['price']/100);
                //星级
                $star += 1;
                //预期收益
                // $sac += ($mill['earnings']/$mill['period'])/($price*$rate);
                $sac += ($mill['earnings']/$mill['period'])/($localprice);

            }
        }
        if($star==3){
            $star = 5;
        }
        $list['force'] = $force;
        $list['sac'] = $sac;
        $list['star'] = $star;
        $this->success('操作成功',$list);
    }
    /**
     * 我的团队
     */
    public function myteam(){
        $user = $this->auth->getUser();
        //获取规则
        $data['rule'] = config('site.rule');
        //获取一级推荐人是自己的人
        $list = db('user')->field('id,username,nickname')->where(['first'=>$user->id,'del'=>1])->select();
        // foreach($list as $k=>$v){
        //     $mesg = db('user_certification')->field('realname')->where(['user_id'=>$v['id']])->find();
        //     $list[$k]['mesg'] = $mesg['realname'];
        //有效人数
        $data['myTeamCount'] = User::getMyTeamCount($user->id);
        $data['user'] = $list;
        $this->success('操作成功',$data);
    }
    /**
     * 获取此人下级的接口
     */
    public function getlower(){
        $user = $this->auth->getUser();
        $user_id = input('user_id');
        if(empty($user_id)){
            $this->error('缺少参数');
        }
        $user = db('user')->where(['id'=>$user_id])->find();
        if(empty($user)){
            $this->error('用户不存在');
        }
        $list = db('user')->field('id,username,nickname')->where(['first'=>$user_id,'del'=>1])->select();
        // foreach($list as $k=>$v){
        //     $mesg = db('user_certification')->field('realname')->where(['user_id'=>$v['id']])->find();
        //     $list[$k]['mesg'] = $mesg['realname'];
        // }
        $this->success('操作成功',$list);
    }
    /**
     * SAC详情页
     */
    public function sacdetail(){
        $time = $this->request->request('time');
        $date = '';
        $user = $this->auth->getUser();
        $data = Http::get(config('sac_url'));
        $data = json_decode($data, true);
        $rate = floatval(config('site.rate'));
        $price = round(config('site.localprice')/$rate,4);        //比特币
        $count = count($data['price_usd']);     //比特币
        $data['price_usd'][$count-1][1] = $price;
        $volume = end($data['volume_usd'])[1];
        $market = end($data['market_cap_usd'])[1];
        // $data = $data['price_usd'][$count-1]; 
       
//        $this->amplitude($price,$data['price_usd'][0]);
//        exit;
        $data = [
            'cny' => $user->cny,
            'sac' => $user->sac,
            'price' => $price,
            'volume' => $volume * $rate,
            'market' => $market,
            'rate'  => $rate,
            'Kline' => $data,
        ];
        $this->success('success', $data);

    }
    /**
     * 收取接口
     */
    public function getequity(){
        $user = $this->auth->getUser();
        //购买股权的id
        $id = input('id');
        if(!$id){
            $this->error('缺少参数');
        }
        //提取的股数
        $num = input('num');
        if($num<=0){
            $this->error('数量不正确');
        }
        //交易密码
        $pay_password = input('pay_password');
        if(empty($pay_password)){
            $this->error('交易密码不能空');
        }
        //判断密码正确
        $pay_password = $this->auth->getEncryptPassword($pay_password, $user->salt);
        if ($user->pay_password != $pay_password) {
            $this->error('支付密码不正确');
        }
        //查这条记录的信息
        $equity = db('user_equity')->where(['id'=>$id,'status'=>1])->find();
        if(empty($equity)){
            $this->error('股权已收取');
        }
        if($num>$equity['money']){
            $this->error('数量不足');
        }
        //返还这个人的本金和利息
        $money = $num;
        $r = db('user')->where(['id'=>$equity['user_id']])->setInc('cny',$money);
        //减少基金
        db('user_equity')->where(['id'=>$equity['id']])->setInc('t_money',$money);
        db('user_equity')->where(['id'=>$equity['id']])->setDec('money',$money);
        //增加提现记录
        $data['user_id'] = $equity['user_id'];
        $data['user_equity_id'] = $equity['id'];
        $data['num'] = $num;
        $data['addtime'] = time();
        db('equity_tixian')->insert($data);
        //做记录
        account_log($equity['user_id'],$money,$user->cny + $money + $user->freeze_cny,0,$user->sac+$user->freeze_sac,'用户ID:'.$user->id.'提取基金'.$money.'cny');
        //更改此条记录的状态
        if($num==$equity['money']){
            $res = db('user_equity')->where(['id'=>$id])->update(['status'=>2]);
        }
        $this->success('操作成功');
    }
    /**
     * 矿机收益明细
     */
    public function milldetail(){
        $user = $this->auth->getUser();
        $id = input('id');
        if($id){
            $where['user_mill'] = $id;
          	\think\Session::set('mill_id',$id);
        }else{
          	$id = \think\Session::get('mill_id');
         	$where['user_mill'] = $id;
        }
        //sac 大于0的是矿机产生的币
        $where['user_id'] = $user->id;
        $where['sac'] = ['>',0];
        $where['desc'] = ['like','%产sac%'];
        $page = input('page')?input('page'):1;
        $limit = input('limit')?input('limit'):10;
        $list = db('user_account_log')->where($where)->order('change_time desc')->page($page,$limit)->select();
        
        $count = db('user_account_log')->where($where)->order('change_time desc')->count();
        $total = db('user_account_log')->where($where)->order('change_time desc')->sum('sac');
        $data['list'] = $list;
        $count = ceil($count/$limit);
        $data['count'] = $count;
        $data['total'] = $total;
        $this->success('操作成功',$data);
    }
    /**
     * 挖宝攻略
     */
    public function indian_strategy(){
        $data = config('site.indian_strategy');
        $this->success('操作成功',$data);
    }
    /**
     * 挖宝规则
     */
    public function indian_rule(){
        $data = config('site.indian_rule');
        $this->success('操作成功',$data);
    }
    /**
     * 体现接口
     */
    public function getmoney(){
        $user = $this->auth->getUser();
        //提现金额
        $num = input('num');
        if($num<100){
            $this->error('提现数量不能少于100');
        }
        if($num>$user->cny){
            $this->error('数量不足');
        }
        //支付密码
        $pay_password = input('pay_password');
        if(empty($pay_password)){
            $this->error('密码不能空');
        }
        //判断密码正确
        $pay_password = $this->auth->getEncryptPassword($pay_password, $user->salt);
        if ($user->pay_password != $pay_password) {
            $this->error('支付密码不正确');
        }
        //扣除提现金额
        $res = db('user')->where(['id'=>$user->id])->setInc('freeze_cny',$num);
        $res1 = db('user')->where(['id'=>$user->id])->setDec('cny',$num);
        //加入提现表
        $data['user_id'] = $user->id;
        $data['num'] = $num;
        $data['fee'] = $num*0.01;
        $data['status'] = 1;
        $data['addtime'] = time();
        $r = db('withdrawal')->insert($data);
        if($r){
            $this->success('提交成功,等待审核');
        }else{
            $this->error('网络错误');
        }
    }
    /**
     * 提现记录接口
     */
    public function getmonetlist(){
        $user = $this->auth->getUser();
        $page = input('page')?input('page'):1;
        $limit = input('limit')?input('limit'):8;
        //开始时间
        $start = input('start');
        //结束时间
        $end = input('end');
        if($start){
            $start = strtotime($start);
            $where['addtime'] = ['>',$start];
        }
        if($end){
            $end = strtotime($end);
            $where['addtime'] = ['<',$end];
        }
        if($start && $end){
            $where['addtime'] = ['between',[$start,$end]];
        }
        $status = input('status');
        if($status){
            $where['status'] = $status;
        }
        
        $where['user_id'] = $user->id;
        $list = db('withdrawal')->where($where)->order('addtime desc')->page($page,$limit)->select();
        $this->success('查询成功',$list);
    }
  	/**
     * 团队奖金
     */
    public function teambonus(){
        $user = $this->auth->getUser();
        //矿机产生的奖励
        $where['desc'] = ['like','%矿机产币分成%'];
        $where['user_id'] = $user->id;
        $k_count = db('user_account_log')->where($where)->sum('sac');
        //股权产生的奖励
        $where1['desc'] = ['like','%基金利润分成%'];
        $where1['user_id'] = $user->id;
        $g_count = db('user_account_log')->where($where1)->sum('cny');
      	$data['k_count'] = $k_count;
        $data['g_count'] = $g_count;
      	if($user->id==983416){
          	$data['k_count'] = 3458.5732;
        	$data['g_count'] = 42548.2648;
        }
       	if($user->id==725861){
          	$data['k_count'] = $k_count+800;
        	$data['g_count'] = $g_count+10000;
        }
     	if($user->id==721863){
          	$data['k_count'] = $k_count+2000;
        	$data['g_count'] = $g_count+25000;
        }
        $this->success('操作成功',$data);
    }
    /**
     * 矿机奖励
     */
    public function millbonus(){
        $type = input('type')?input('type'):1;
        
        $user = $this->auth->getUser();
        $page = input('page')?input('page'):1;
        $limit = input('limit')?input('limit'):8;
        $where['desc'] = ['like','%矿机产币分成%'];
        $where['user_id'] = $user->id;
        if($type==1){
            $count = db('user_account_log')->where($where)->whereTime('change_time','yesterday')->count();
            $list = db('user_account_log')->field('desc,sac,change_time')->where($where)->whereTime('change_time','yesterday')->page($page,$limit)->order('change_time desc')->select();
        }else{
            $count = db('user_account_log')->where($where)->count();
            $list = db('user_account_log')->field('desc,sac,change_time')->where($where)->page($page,$limit)->order('change_time desc')->select();
        }
        
        foreach($list as $k=>$v){
            $list[$k]['change_time'] = date('Y-m-d H:i:s',$v['change_time']);
        }
        $data['count'] = $count;
        $data['list'] = $list;
        $this->success('操作成功',$data);
    }
    /**
     * 基金奖励
     */
    public function fundbonus(){
        $type = input('type')?input('type'):1;
        $user = $this->auth->getUser();
        $page = input('page')?input('page'):1;
        $limit = input('limit')?input('limit'):8;
        $where['desc'] = ['like','%基金利润分成%'];
        $where['user_id'] = $user->id;
        if($type==1){
            $count = db('user_account_log')->where($where)->whereTime('change_time','yesterday')->count();
            $list = db('user_account_log')->field('desc,cny,change_time')->where($where)->whereTime('change_time','yesterday')->page($page,$limit)->order('change_time desc')->select();
        }else{
            $count = db('user_account_log')->where($where)->count();
            $list = db('user_account_log')->field('desc,cny,change_time')->where($where)->page($page,$limit)->order('change_time desc')->select();
        }
        
        foreach($list as $k=>$v){
            $list[$k]['change_time'] = date('Y-m-d H:i:s',$v['change_time']);
           // $list[$k]['sac'] = $v['cny'];
        }
        $data['count'] = $count;
        $data['list'] = $list;
        $this->success('操作成功',$data);
    }
}
